/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.fastcase.item.service.impl;

import com.icinfo.cloud.common.core.Constant.Constant;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.punish.fastcase.item.mapper.SearchRecordMapper;
import com.icinfo.cloud.provider.punish.fastcase.item.service.ISearchRecordService;
import com.icinfo.cloud.provider.punish.item.model.SearchRecord;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 描述: 事项搜索记录表 search_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年11月30日
 */
@Service
@Slf4j
public class SearchRecordServiceImpl extends MyBatisServiceSupport implements ISearchRecordService {

    @Resource
    private SearchRecordMapper searchRecordMapper;

    /**
     * 新增搜索记录
     *
     * @param searchRecord 搜索记录参数实体
     * @return java.lang.Boolean
     * @author liuyongfei
     * @date 2022/11/30
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSearchRecord(SearchRecord searchRecord) {
        try {
            UserDTO userInfo = UserUtil.getUserInfo();
            assert userInfo != null;
            searchRecord.setUserId(userInfo.getUserId().toString());
            searchRecord.setId(StringUtils.uuid());
            searchRecord.setCreated(new Date());

            List<SearchRecord> searchRecordList = getSearchRecordList();

            //已存在进行修改
            SearchRecord exists =
                    searchRecordList.stream().filter(r -> r.getSearchText().equals(searchRecord.getSearchText())).findAny().orElse(null);
            if (Objects.nonNull(exists)) {
                exists.setCreated(new Date());
                return searchRecordMapper.updateByPrimaryKey(exists) > 0;
            }

            searchRecordList.add(0, searchRecord);

            //超过十条，先删除再新增
            if (searchRecordList.size() > Constant.INTEGER_10) {
                deleteSearchRecord();
                searchRecordList = new ArrayList<>(searchRecordList.subList(0, 10));
                searchRecordList.forEach(record -> searchRecordMapper.insertSelective(record));
            } else {
                //未超过10条直接新增
                searchRecordMapper.insertSelective(searchRecord);
            }
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /**
     * 删除当前用户的搜索记录
     *
     * @return java.lang.Boolean
     * @author liuyongfei
     * @date 2022/11/30
     */
    @Override
    public Boolean deleteSearchRecord() {
        Example example = new Example(SearchRecord.class);
        UserDTO userInfo = UserUtil.getUserInfo();
        assert userInfo != null;
        example.createCriteria().andEqualTo("userId", userInfo.getUserId().toString());
        return searchRecordMapper.deleteByExample(example) > 0;
    }

    /**
     * 获取当前用户的搜索记录
     *
     * @return java.util.List<com.icinfo.cloud.provider.item.model.SearchRecord>
     * @author liuyongfei
     * @date 2022/11/30
     */
    @Override
    public List<SearchRecord> getSearchRecordList() {
        UserDTO userInfo = UserUtil.getUserInfo();
        assert userInfo != null;
        Example example = new Example(SearchRecord.class);
        example.createCriteria().andEqualTo("userId", userInfo.getUserId().toString());
        example.orderBy("created").desc();
        return searchRecordMapper.selectByExample(example);
    }
}